import {
  DeleteOutlined,
  EditOutlined,
  FileOutlined,
  FolderOpenOutlined,
  PlusOutlined,
  SaveOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import {
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from "@ant-design/pro-components";
import {
  Badge,
  Button,
  Col,
  Form,
  Input,
  Popconfirm,
  Row,
  Space,
  Switch,
  Tag,
  Tree,
  Typography,
  message,
} from "antd";

import React, { useMemo, useState } from "react";

import "./index.less";

const { Title, Paragraph, Text } = Typography;
// const { Search } = Input;

interface MenuNode {
  key: string;
  title: string;
  type: "folder" | "file";
  children?: MenuNode[];
  visible?: boolean;
  permissions?: string[];
}

const initialTree: MenuNode[] = [
  {
    key: "1",
    title: "内容管理",
    type: "folder",
    children: [
      { key: "1-1", title: "文章列表", type: "file" },
      { key: "1-2", title: "分类管理", type: "file" },
      { key: "1-3", title: "评论管理", type: "file" },
    ],
  },
  {
    key: "2",
    title: "系统设置",
    type: "folder",
    children: [
      { key: "2-1", title: "角色权限", type: "file" },
      { key: "2-2", title: "菜单配置", type: "file" },
    ],
  },
  {
    key: "3",
    title: "用户中心",
    type: "folder",
    children: [
      { key: "3-1", title: "用户列表", type: "file" },
      { key: "3-2", title: "标签管理", type: "file" },
    ],
  },
];

const Page42: React.FC = () => {
  const [treeData, setTreeData] = useState<MenuNode[]>(initialTree);
  const [selectedKey, setSelectedKey] = useState<string | null>(null);
  const [keyword, setKeyword] = useState<string>("");
  const [form] = Form.useForm();

  const flatCount = useMemo(() => {
    const walk = (nodes: MenuNode[]): number =>
      nodes.reduce(
        (acc, n) => acc + 1 + (n.children ? walk(n.children) : 0),
        0,
      );
    return walk(treeData);
  }, [treeData]);

  type AntTreeNode = {
    key: string;
    title: React.ReactNode;
    children?: AntTreeNode[];
  };

  const toAntTree = (nodes: MenuNode[]): AntTreeNode[] =>
    nodes.map((n) => ({
      key: n.key,
      title: (
        <div className="custom-tree-node">
          <div className="node-content">
            {n.type === "folder" ? (
              <FolderOpenOutlined className="node-icon" />
            ) : (
              <FileOutlined className="node-icon" />
            )}
            <span className="node-text">{n.title}</span>
            {n.visible === false && (
              <Tag color="default" className="node-tag">
                隐藏
              </Tag>
            )}
            {n.permissions && n.permissions.length > 0 && (
              <Badge count={n.permissions.length} className="node-badge" />
            )}
          </div>
          <div className="node-actions">
            <Space size={4}>
              <Button
                size="small"
                type="text"
                icon={<EditOutlined />}
                onClick={(e) => onEditNode(e, n)}
              />
              <Popconfirm
                title="确认删除该节点？"
                onConfirm={() => onRemoveNode({} as React.MouseEvent, n.key)}
              >
                <Button
                  size="small"
                  danger
                  type="text"
                  icon={<DeleteOutlined />}
                />
              </Popconfirm>
            </Space>
          </div>
        </div>
      ),
      children: n.children ? toAntTree(n.children) : undefined,
    }));

  const handleSelect = (keys: React.Key[]) => {
    const k = (keys[0] as string) || null;
    setSelectedKey(k);
    if (!k) return;
    const node = findNodeByKey(treeData, k);
    if (node) {
      form.setFieldsValue({
        title: node.title,
        type: node.type,
        visible: node.visible !== false,
        permissions: node.permissions || [],
        desc: `${node.title} 的描述...`,
      });
    }
  };

  const findNodeByKey = (nodes: MenuNode[], key: string): MenuNode | null => {
    for (const n of nodes) {
      if (n.key === key) return n;
      if (n.children) {
        const found = findNodeByKey(n.children, key);
        if (found) return found;
      }
    }
    return null;
  };

  const updateNodeByKey = (
    nodes: MenuNode[],
    key: string,
    patch: Partial<MenuNode>,
  ): MenuNode[] =>
    nodes.map((n) =>
      n.key === key
        ? { ...n, ...patch }
        : n.children
          ? { ...n, children: updateNodeByKey(n.children, key, patch) }
          : n,
    );

  const onEditNode = (e: React.MouseEvent, node: MenuNode) => {
    e.stopPropagation();
    setSelectedKey(node.key);
    form.setFieldsValue({
      title: node.title,
      type: node.type,
      visible: node.visible !== false,
      permissions: node.permissions || [],
      desc: `${node.title} 的描述...`,
    });
  };

  const onRemoveNode = (_e: React.MouseEvent, key: string) => {
    const drop = (nodes: MenuNode[]): MenuNode[] =>
      nodes
        .filter((n) => n.key !== key)
        .map((n) => (n.children ? { ...n, children: drop(n.children) } : n));
    setTreeData((prev) => drop(prev));
    if (selectedKey === key) setSelectedKey(null);
    message.success("已删除节点");
  };

  const onCreateNode = (type: "folder" | "file") => {
    const newKey = `${Date.now()}`;
    setTreeData((prev) => [
      ...prev,
      { key: newKey, title: type === "folder" ? "新建目录" : "新建页面", type },
    ]);
    message.success("已创建");
  };

  const onSave = async () => {
    if (!selectedKey) {
      message.warning("请先选择左侧菜单节点");
      return;
    }
    const values = await form.validateFields();
    setTreeData((prev) =>
      updateNodeByKey(prev, selectedKey, {
        title: values.title,
        type: values.type,
        visible: values.visible,
        permissions: values.permissions,
      }),
    );
    message.success("已保存");
  };

  const filteredTree = useMemo(() => {
    if (!keyword) return treeData;
    const match = (nodes: MenuNode[]): MenuNode[] =>
      nodes
        .map((n) => ({
          ...n,
          children: n.children ? match(n.children) : undefined,
        }))
        .filter(
          (n) =>
            n.title.toLowerCase().includes(keyword.toLowerCase()) ||
            (n.children && n.children.length > 0),
        );
    return match(treeData);
  }, [keyword, treeData]);

  return (
    <div className="tree-menu-page">
      <div className="page-header">
        <Title level={2} className="page-title">
          多级树形菜单管理
        </Title>
        <Paragraph className="page-description">
          支持搜索、增删改、显示控制与权限标记的菜单管理，配合表单编辑右侧详情
        </Paragraph>
      </div>

      <div className="menu-stats">
        <div className="stat-card">
          <div className="stat-title">节点总数</div>
          <div className="stat-value">{flatCount}</div>
        </div>
        <div className="stat-card">
          <div className="stat-title">已选择</div>
          <div className="stat-value">{selectedKey ? 1 : 0}</div>
        </div>
        <div className="stat-card">
          <div className="stat-title">过滤关键字</div>
          <div className="stat-value">{keyword || "-"}</div>
        </div>
      </div>

      <div className="content-container">
        <div className="menu-sidebar">
          <div className="sidebar-header">
            <span className="header-title">菜单树</span>
            <Space>
              <Button
                size="small"
                icon={<PlusOutlined />}
                onClick={() => onCreateNode("folder")}
              >
                新目录
              </Button>
              <Button
                size="small"
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => onCreateNode("file")}
              >
                新页面
              </Button>
            </Space>
          </div>
          <div className="tree-container">
            <Input
              allowClear
              prefix={<SearchOutlined />}
              placeholder="搜索菜单"
              value={keyword}
              onChange={(e) => setKeyword(e.target.value)}
              className="search-container"
            />
            <Tree
              showLine
              defaultExpandAll
              onSelect={handleSelect}
              treeData={toAntTree(filteredTree)}
              height={520}
            />
          </div>
          <div className="sidebar-footer">
            <div className="total-items">共 {flatCount} 项</div>
            <Button type="link" size="small" onClick={() => setKeyword("")}>
              清空搜索
            </Button>
          </div>
        </div>

        <div className="content-main">
          <div className="form-container">
            <div className="form-title">节点详情</div>
            <ProForm
              form={form}
              submitter={{
                render: () => (
                  <div className="form-footer">
                    <Button onClick={() => form.resetFields()}>重置</Button>
                    <Button
                      type="primary"
                      icon={<SaveOutlined />}
                      onClick={onSave}
                    >
                      保存
                    </Button>
                  </div>
                ),
              }}
            >
              <Row gutter={16}>
                <Col span={12}>
                  <ProFormText
                    name="title"
                    label="标题"
                    placeholder="请输入节点标题"
                    rules={[{ required: true }]}
                  />
                </Col>
                <Col span={12}>
                  <ProFormSelect
                    name="type"
                    label="类型"
                    options={[
                      { label: "目录", value: "folder" },
                      { label: "页面", value: "file" },
                    ]}
                    rules={[{ required: true }]}
                  />
                </Col>
              </Row>
              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    name="visible"
                    label="是否显示"
                    valuePropName="checked"
                  >
                    <Switch />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <ProFormSelect
                    name="permissions"
                    label="权限标记"
                    mode="multiple"
                    options={[
                      { label: "查看", value: "read" },
                      { label: "新建", value: "create" },
                      { label: "编辑", value: "update" },
                      { label: "删除", value: "delete" },
                    ]}
                  />
                </Col>
              </Row>
              <ProFormTextArea
                name="desc"
                label="描述"
                placeholder="请输入描述"
                rows={4}
              />
            </ProForm>
          </div>

          <div className="preview-container" style={{ marginTop: 24 }}>
            <div className="preview-title">预览区</div>
            <div className="preview-content">
              {selectedKey ? (
                <Text>已选择节点：{selectedKey}</Text>
              ) : (
                <Text type="secondary">请选择左侧任一节点查看详情</Text>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Page42;
